import { query, mutation, baseImgUrl } from '@/utils/http'

function apiPublish(token, params) {
  const str = `
    ($request:UserMicroblogInput!){
      addUserMicroblog(request:$request)
    }
  `
  return mutation(token, str, { request: params })
}

function apiGetPosts(token, params) {
  const str = `
    ($request:UserMicroblogQueryRequest!){
      queryUserMicroBlogs(request:$request){
        page{
          hasNext
        }
        datas{
          rownum
          id
          createTime
          wechatUser{
            nickname
            headImgUrl
          }
          intros{
            id
            type
            content
          }
        }
      }
    }
  `
  return new Promise((resolve, reject) => {
    query(token, str, { request: params })
      .then(res => {
        if (res.data.data && res.data.data.queryUserMicroBlogs) {
          const result = res.data.data.queryUserMicroBlogs
          const posts = result.datas
          const hasNext = result.page.hasNext
          const last = result.datas.length ? result.datas[result.datas.length - 1].rownum : 0
          // formate
          const list = posts.map(v => ({
            id: v.id,
            date: v.createTime,
            author: v.wechatUser.nickname,
            avatar: v.wechatUser.headImgUrl,
            img: baseImgUrl + v.intros.find(o => o.type === 'image').content,
            text: v.intros.find(o => o.type === 'text').content
          }))
          // 打乱顺序
          const sortList =
            list.length > 3 ? [...list].slice(1).sort(() => 0.5 - Math.random()) : list
          resolve({
            posts: list.length > 3 ? [list[0], ...sortList] : list,
            hasNext,
            last
          })
        } else {
          reject(new Error('fail'))
        }
      })
      .catch(err => reject(err))
  })
}

function apiDeletePost(token, id) {
  const str = `
    ($id:Long!){
      deleteUserMicroblog(id:$id)
    }
  `
  return new Promise((resolve, reject) => {
    mutation(token, str, { id })
      .then(res => {
        res.data.data && res.data.data.deleteUserMicroblog ? resolve() : reject(new Error('fail'))
      })
      .catch(err => {
        reject(err)
      })
  })
}

export { apiPublish, apiGetPosts, apiDeletePost }
